<template>
  <div class="box">
    <div class="tool-bar">
      <div>{{ pdfParams.pageNumber }} / {{ pdfParams.total }}</div>
      <el-button type="primary" :disabled="pdfParams.pageNumber == 1" @click="prevPage"
        >上一页</el-button
      >
      <el-button
        type="primary"
        :disabled="pdfParams.pageNumber == pdfParams.total"
        @click="nextPage"
        >下一页</el-button
      >
      <!-- <el-popover
        placement="top-start"
        title="全屏"
        :width="200"
        trigger="hover"
        content="键盘上/左为上一页，下/右为下一页"
      >
        <template #reference>
          <el-icon style="cursor: pointer" @click="handleFullScreen"
            ><FullScreen
          /></el-icon>
        </template>
      </el-popover> -->
    </div>
    <canvas ref="canvasRef" id="pdf-render"></canvas>
  </div>
  <!-- 右侧按钮组 -->
  <div class="pdf-viewer-buttons">
    <el-button class="pdf-viewer-item" circle size="large" @click="handleLarger">
      <el-icon><Plus /></el-icon>
    </el-button>
    <el-button class="pdf-viewer-item" circle size="large" @click="handleSmaller">
      <el-icon><Minus /></el-icon>
    </el-button>
    <!-- <el-button class="pdf-viewer-item" circle size="large" @click="handleDownload">
      <el-icon><Download /></el-icon>
    </el-button> -->
  </div>
</template>
<script setup>
import { onMounted, reactive } from "vue";
import { Plus, Minus, Download } from "@element-plus/icons-vue";
import { saveAs } from "file-saver";
import { FullScreen } from "@element-plus/icons-vue";
// import * as pdfjsLib from "../../../public/pdfjs/build/pdf.mjs";
// pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
//   "../../../public/pdfjs/build/pdf.worker.mjs",
//   import.meta.url
// ).toString();

const props = defineProps({
  fileUrl: String,
  filename: String,
});

const canvasRef = ref(null);
const pdfParams = reactive({
  pageNumber: 1, // 当前页
  total: 0, // 总页数
  pdfScale: window.screen.width > 1840 ? 6.5 : 4.5, //缩放比例
});
console.log(window.screen.width);
onMounted(async () => {
  // 设置 worker 路径（重要！）
  // pdfjsLib.GlobalWorkerOptions.workerSrc =
  // 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.4.120/build/pdf.worker.min.js';

  getPdfView();
});

const getPdfView = async (number) => {
  const loadingTask = pdfjsLib.getDocument(props.fileUrl);
  const pdf = await loadingTask.promise;
  // 渲染第一页
  const page = await pdf.getPage(number ? number : pdfParams.pageNumber);
  pdfParams.total = pdf.numPages; // 获取总页数
  const viewport = page.getViewport({ scale: pdfParams.pdfScale });
  const context = canvasRef.value.getContext("2d");
  canvasRef.value.height = viewport.height;
  canvasRef.value.width = viewport.width;
  await page.render({
    canvasContext: context,
    viewport: viewport,
  }).promise;
};

// 加载pdf的某一页
const getPdfPage = (number) => {
  page.getPage(number).then((page) => {
    // const scale = 1.5;
    const viewport = page.getViewport({ scale: pdfParams.pdfScale });
    const outputScale = window.devicePixelRatio || 1;
    console.log(viewport);
    const canvas = document.getElementById("pdf-render");
    const context = canvas.getContext("2d");
    canvas.width = Math.floor(viewport.width * outputScale);
    canvas.height = Math.floor(viewport.height * outputScale);
    canvas.style.width = Math.floor(viewport.width) + "px";
    canvas.style.height = Math.floor(viewport.height) + "px";
    const transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null;
    const renderContext = {
      canvasContext: context,
      transform: transform,
      viewport: viewport,
    };
    // canvas.width = viewport.viewBox[2]
    // canvas.height = viewport.viewBox[3]
    // viewport.width = viewport.viewBox[2]
    // viewport.height = viewport.viewBox[3]
    // canvas.style.width = Math.floor(viewport.width) + "px"
    // canvas.style.height = Math.floor(viewport.height) + "px"
    // let renderContext = {
    // 	canvasContext: context,
    // 	viewport: viewport,
    // 	// 这里transform的六个参数，使用的是transform中的Matrix(矩阵)
    // 	// transform: [1, 0, 0, -1, 0, viewport.height],
    // }
    // 进行渲染
    page.render(renderContext);
  });
};
// 下一页功能
const prevPage = () => {
  if (pdfParams.pageNumber > 1) {
    pdfParams.pageNumber -= 1;
  } else {
    pdfParams.pageNumber = 1;
  }
  getPdfView(pdfParams.pageNumber);
};
// 上一页功能
const nextPage = () => {
  console.log("111", 111);
  if (pdfParams.pageNumber < pdfParams.total) {
    pdfParams.pageNumber += 1;
  } else {
    pdfParams.pageNumber = pdfParams.total;
  }
  getPdfView(pdfParams.pageNumber);
};

// 放大
const handleLarger = async () => {
  pdfParams.pdfScale = pdfParams.pdfScale + 0.2;
  getPdfView(pdfParams.pageNumber);
};
// 缩小
const handleSmaller = async () => {
  pdfParams.pdfScale = pdfParams.pdfScale - 0.2;
  getPdfView(pdfParams.pageNumber);
};
// 下载
// const handleDownload = () => {
//   const pwdUrl = props.src.split("&decryptStr")[0];
//   saveAs(pwdUrl, props.filename);
// };
//全屏
const handleFullScreen = () => {
  const element = document.getElementById("pdf-render");
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
};

//
onMounted(() => {
  keyDown();
});
const keyDown = () => {
  document.onkeydown = function (event) {
    console.log("event", event);
    const keyCode = (event || window.event || arguments.callee.caller.arguments[0])
      .keyCode;
    console.log("keyCode", keyCode);
    switch (keyCode) {
      case 38: // 上键
        prevPage();
        break;
      case 40: // 下键
        nextPage();
        break;
      case 37: // 左键
        prevPage();
        break;
      case 39: // 右键
        nextPage();
        break;
    }
  };
};
</script>
<style lang="scss" scoped>
/* 分页 跳转 */
.box {
  // width: 100%;
  // height: 100%;
  .tool-bar {
    position: fixed;
    top: 100px;
    right: 50px;
    z-index: 120;
    display: flex;
    flex-direction: row;
    align-items: center;
    // width: 96.5%;
    background-color: #fff;
    button {
      margin: 0 10px;
    }
  }
}
#pdf-render {
  width: 100%;
  height: 100%;
  border: 1px solid rgba(155, 155, 155, 0.2);
  box-shadow: rgba(100, 100, 111, 0.2) 0px 7px 29px 0px;
}
/* 放大缩小下载 */
.pdf-viewer-buttons {
  position: fixed;
  top: 200px;
  right: 60px;
  z-index: 120;

  display: flex;
  flex-direction: column;
}

.pdf-viewer-buttons .pdf-viewer-item {
  margin-top: 15px;
  margin-left: 0 !important;
}
</style>
